var crypto = require('./utils/crypto');
var express = require('express');
var db = require('./utils/db');
var http = require("./utils/http");
var bodyParser = require('body-parser');
var fs = require("fs");

var app = express();
app.use(bodyParser.urlencoded({limit: '50mb',extended: false}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(express.static(__dirname + '/public')); //静态文件目录
app.use("/data",express.static(__dirname + '/data')); //静态文件目录


var config = null;
var hallAddr = "";

function send(res,ret){
	var str = JSON.stringify(ret);
	res.send(str)
}

exports.start = function(cfg){
	config = cfg;
	hallAddr = config.HALL_IP  + ":" + config.CLIENT_PORT;
	app.listen(config.CLIENT_PORT);
	console.log("account server is listening on " + config.CLIENT_PORT);
}

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.post('/upload',function(req,res){
	var name = req.body.name;
    var title = req.body.title;
    var img_info = req.body.img_info;
	var dpr = req.body.dpr;
	var url = "data/" + crypto.md5(img_info) + ".jpg";

	var imageBuffer = crypto.decodeBase64Image(img_info);
	console.log(imageBuffer);
	fs.writeFile(__dirname + "/"+ url, imageBuffer.data, function(err) {
	});

	db.create_ad(name,title,url,dpr,function(row){
		console.log("row:"+row);
		send(res,{url:config.HALL_IP + "/" + url,id:row.insertId});	
	});
});

app.post('/getimgurl',function(req,res){
	db.get_ad(req.query.id,function(row){
		row.url = hallAddr + "/" +row.url;
		send(res,row);
	});
});


// app.post('/wechat',function(req,res){
// 	res.end(sign);
// });

